package cn.chiship.framework.third.biz.wxpub.service.impl;

import cn.chiship.framework.common.constants.CommonCacheConstants;
import cn.chiship.sdk.cache.service.RedisService;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.framework.base.BaseServiceImpl;
import cn.chiship.framework.third.biz.wxpub.mapper.ThirdWechatUserLocationMapper;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatUserLocation;
import cn.chiship.framework.third.biz.wxpub.entity.ThirdWechatUserLocationExample;
import cn.chiship.framework.third.biz.wxpub.service.ThirdWechatUserLocationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 微信用户实时坐标业务接口实现层
 * 2022/9/18
 * @author lijian
 */
@Service
public class ThirdWechatUserLocationServiceImpl extends BaseServiceImpl<ThirdWechatUserLocation,ThirdWechatUserLocationExample> implements ThirdWechatUserLocationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThirdWechatUserLocationServiceImpl.class);
    @Resource
    private RedisService redisService;

    @Resource
    ThirdWechatUserLocationMapper thirdWechatUserLocationMapper;
    @Override
    public void insertOrUpdateSelective(ThirdWechatUserLocation wechatUserLocation) {
        String key= CommonCacheConstants.buildKey(CommonCacheConstants.REDIS_WECHAT_USER_LOCATION_PREFIX);
        BaseResult baseResult = null;
        if(null != wechatUserLocation){
            String item = wechatUserLocation.getAppId() + wechatUserLocation.getOpenId();
            //先检查redis是否有openid
            ThirdWechatUserLocation redisWechatUserLocation = (ThirdWechatUserLocation) redisService.hget(key, item);
            if (null == redisWechatUserLocation) {
                //redis没有数据，则新增
                baseResult=super.insertSelective(wechatUserLocation);
            } else{
                ThirdWechatUserLocationExample wechatUserLocationExample = new ThirdWechatUserLocationExample();
                wechatUserLocationExample.createCriteria().andAppIdEqualTo(wechatUserLocation.getAppId()).andOpenIdEqualTo(wechatUserLocation.getOpenId());
                List<ThirdWechatUserLocation> wechatUserLocations = thirdWechatUserLocationMapper.selectByExample(wechatUserLocationExample);
                if (wechatUserLocations.size()==1){
                    wechatUserLocation.setId(wechatUserLocations.get(0).getId());
                    baseResult=super.updateByPrimaryKeySelective(wechatUserLocation);
                }
            }
            if(baseResult.isSuccess()){
                //缓存到redis
                redisService.hset(key,item,wechatUserLocation);
            }
        }
    }
}
